package com.ecnu.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ecnu.common.core.domain.AjaxResult;
import com.ecnu.common.core.domain.model.LoginUser;
import com.ecnu.common.core.page.PageDomain;
import com.ecnu.common.utils.OtherUtil;
import com.ecnu.common.utils.PageUtils;
import com.ecnu.common.utils.StringUtils;
import com.ecnu.common.utils.uuid.IdUtils;
import com.ecnu.system.domain.ProjectStage;
import com.ecnu.system.domain.ProjectStageMission;
import com.ecnu.system.domain.vo.ProjectStageMissionVO;
import com.ecnu.system.domain.vo.ProjectStageVO;
import com.ecnu.system.mapper.ProjectStageMapper;
import com.ecnu.system.mapper.ProjectStageMissionMapper;
import com.ecnu.system.service.IProjectStageService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * ecnu_活动_阶段表 服务实现类
 * </p>
 *
 * @author zdn
 * @since 2025-03-23
 */
@Service
public class ProjectStageServiceImpl extends ServiceImpl<ProjectStageMapper, ProjectStage> implements IProjectStageService {

    @Autowired
    private ProjectStageMapper projectStageMapper;
    @Autowired
    private ProjectStageMissionMapper stageMissionMapper;

    /**
     * 分页查询
     */
    protected void startPage(PageDomain pageDomain) {
        PageUtils.startPage(pageDomain);
    }

    protected String getId() {
        return IdUtils.fastSimpleUUID();
    }

    protected String getUuId() {
        return IdUtils.fastUUID();
    }

    @Override
    public AjaxResult listByProId(String proId) {
        try {
            QueryWrapper<ProjectStage> wrapper = new QueryWrapper<>();
            wrapper.eq("pro_id", proId);
            wrapper.eq("del_flag", "0");
            List<ProjectStage> projectStages = projectStageMapper.selectList(wrapper);

            List<ProjectStageVO> list = OtherUtil.copy(projectStages, ProjectStageVO.class);

            if (!list.isEmpty()) {
                //取阶段ID
                List<String> fileList = list.stream()
                        .map(ProjectStageVO::getId)
                        .collect(Collectors.toList());
                //取阶段任务
                List<ProjectStageMission> missionList = stageMissionMapper.selectList(
                        new QueryWrapper<ProjectStageMission>().in("stage_id", fileList));
                List<ProjectStageMissionVO> missionVOS = OtherUtil.copy(missionList, ProjectStageMissionVO.class);

                //按照阶段组装任务列表
                Map<String, List<ProjectStageMissionVO>> stringListMap = missionVOS.stream()
                        .collect(Collectors.groupingBy(ProjectStageMissionVO::getStageId));
                //组装任务列表
                list.forEach(a -> {
                    List<ProjectStageMissionVO> userList = stringListMap.get(a.getId());
                    a.setMissionList(userList == null ? new ArrayList<>() : userList);
                });
            }
            return AjaxResult.success(list);
        } catch (InvocationTargetException | NoSuchMethodException | InstantiationException | IllegalAccessException
                e) {
            log.error("阶段查询错误：" + e.getMessage());
            return AjaxResult.error("查询失败，请联系管理员");
        }
    }

    @Override
    public AjaxResult del(String id) {
        ProjectStage stage = new ProjectStage();
        stage.setId(id);
        stage.setDelFlag("2");
        int i = projectStageMapper.updateById(stage);
        return AjaxResult.success("删除成功", i);
    }

    @Override
    public AjaxResult edit(ProjectStage dto, LoginUser loginUser) {
        Boolean save = false;
        if (StringUtils.isBlank(dto.getId())) {
            dto.setId(getId());
            dto.setCreateUser(String.valueOf(loginUser.getUserId()));
            save = save(dto);

        } else {
            save = updateById(dto);
        }
        return save ? AjaxResult.success("保存成功") : AjaxResult.error("保存失败");
    }
}
